package araxy.blog.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class JsonUtil {
    public static final String NullJSONString = "{}";
    public static final String FlgTrueJSONString = "{\"flg\":true}";
    public static final String FlgFalseJSONString = "{\"flg\":false}";

    public static String ObjectToJsonString(Object obj) throws JsonProcessingException {
        ObjectMapper om = new ObjectMapper();
        return om.writeValueAsString(obj);
    }

    public static <T>T JsonStringToObject( String str, Class<T> c){
        if("".equals(str) || c == null){
            return null;
        }
        ObjectMapper om = new ObjectMapper();
        try {
            return om.readValue(str,c);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> Collection<T> JsonStringToCollection(String str, Class<?> cc, Class<T> el) {
        if("".equals(str) || cc == null || el == null){
            return null;
        }
        ObjectMapper om = new ObjectMapper();
        JavaType javaType = om.getTypeFactory().constructParametricType(cc, el);
        Collection<T> c = null;
        try {
            c = om.readValue(str,javaType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return c;
    }

    public static <T> List<T> JsonStringToList(String str, Class<?> l,Class<T> el) {
        return (List<T>) JsonStringToCollection(str,l,el);
    }

    public static <K,V> Map<K,V> JsonStringToMap(String str, Class<?> mc, Class<K> k,Class<V> v) {
        if("".equals(str) || mc == null || k == null || v == null){
            return null;
        }
        ObjectMapper om = new ObjectMapper();
        JavaType javaType = om.getTypeFactory().constructParametricType(mc,k,v);
        Map<K,V> m = null;
        try {
            m = om.readValue(str,javaType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return m;
    }

}
